import {useParams} from "react-router-dom";
import {getQuestionService} from "../services/question";
import {useRequest} from "ahooks";
import {useEffect} from "react";
import {useDispatch} from "react-redux";
import {resetComponents} from "../store/componentsReducer";
import {resetPageInfo} from "../store/pageInfoReducer";

function useLoadQuestionData() {

    const dispatch = useDispatch()
    const {id = ''} = useParams()

    const {data, loading, error, run} =
        useRequest(async (id: string) => {
            if (!id) throw new Error('没有问卷 id')
            return await getQuestionService(id)
        }, {
            manual: true
        })
    useEffect(() => {
        if (!data) return
        const {title = '', componentList = [], desc = '', js = '', css = '', isPublished = false} = data
        let selectedId = componentList.length > 0 ? componentList[0].fe_id : ''
        dispatch(resetComponents({componentList, selectedId, copiedComponent: null}))
        dispatch(resetPageInfo({title, desc, js, css,isPublished}))
    }, [data]);
    useEffect(() => {
        run(id)
    }, [id])
    return {
        loading,
        error
    }
}

export default useLoadQuestionData